/**
 * Contract Updates Admin Page
 * Main page for managing contract parameter updates
 */

'use client';

import React, { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { AlertTriangle, Settings, RefreshCw, Shield, Activity } from 'lucide-react';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { DashboardLayout } from '@/components/layout/dashboard-layout';
import { AdminGuard } from '@/components/auth/PermissionGuard';
import { useTranslation } from 'react-i18next';
import ContractUpdateManager from '@/components/contract/ContractUpdateManager';
import ContractMonitoringDashboard from '@/components/contract/ContractMonitoringDashboard';

const ContractUpdatesPage = () => {
  const { t } = useTranslation('common');
  const [activeContract, setActiveContract] = useState('dtv_token');
  const [activeTab, setActiveTab] = useState('updates');

  const contractInfo = {
    dtv_token: {
      name: t('contractUpdates.contracts.dtv_token.name', 'DTV 代幣'),
      address: '0xC39B3d7fc61287047A9795E07961AD4562689cEd',
      description: t('contractUpdates.contracts.dtv_token.description', '主要 BEP-20 代幣合約，具有手續費和反機器人機制'),
      riskLevel: 'high',
      updateableParams: [
        t('contractUpdates.parameters.transactionFeeRate', '交易手續費率'),
        t('contractUpdates.parameters.burnFeeRate', '銷毀手續費率'),
        t('contractUpdates.operations.setAntiBotConfig.name', '反機器人配置'),
        t('contractUpdates.operations.setFeeExemption.name', '手續費豁免'),
        t('contractUpdates.operations.setBlacklist.name', '黑名單管理')
      ]
    },
    dtv_mining: {
      name: t('contractUpdates.contracts.dtv_mining.name', 'DTV 挖礦'),
      address: '0xD94bF46aF1Bacc4721C1B321785E24c61DBf58D4',
      description: t('contractUpdates.contracts.dtv_mining.description', '處理 POS/POP 計算和獎勵的挖礦合約'),
      riskLevel: 'medium',
      updateableParams: [
        t('contractUpdates.parameterOptions.mining_release_rate', '挖礦釋放率'),
        t('contractUpdates.parameterOptions.reward_distribution_rate', '獎勵分配率'),
        t('contractUpdates.parameterOptions.daily_reward_cap', '每日獎勵上限')
      ]
    },
    dtv_vesting: {
      name: t('contractUpdates.contracts.dtv_vesting.name', 'DTV 鎖倉'),
      address: '0x5FBda2E9440a170c17a03034732122817a45218b',
      description: t('contractUpdates.contracts.dtv_vesting.description', '受控釋放的代幣鎖倉合約'),
      riskLevel: 'low',
      updateableParams: [
        t('contractUpdates.updateableParams', '鎖倉參數'),
        t('contractUpdates.updateableParams', '釋放計劃')
      ]
    },
    dtv_nft: {
      name: t('contractUpdates.contracts.dtv_nft.name', 'DTV NFT'),
      address: '0x552201516ec3612B04a275C878F6E7DA5E4af9Bc',
      description: t('contractUpdates.contracts.dtv_nft.description', '特權系統的 NFT 合約'),
      riskLevel: 'low',
      updateableParams: [
        t('contractUpdates.updateableParams', 'NFT 特權'),
        t('contractUpdates.updateableParams', '倍數設定')
      ]
    }
  };

  const getRiskBadge = (riskLevel: string) => {
    const riskConfig = {
      high: { color: 'bg-red-100 text-red-800', label: t('contractUpdates.riskLevels.high', '高風險') },
      medium: { color: 'bg-yellow-100 text-yellow-800', label: t('contractUpdates.riskLevels.medium', '中風險') },
      low: { color: 'bg-green-100 text-green-800', label: t('contractUpdates.riskLevels.low', '低風險') }
    };
    
    const config = riskConfig[riskLevel as keyof typeof riskConfig];
    return (
      <Badge className={config.color}>
        <Shield className="w-3 h-3 mr-1" />
        {config.label}
      </Badge>
    );
  };

  const contractList = Object.entries(contractInfo);

  return (
    <DashboardLayout>
      <AdminGuard>
        <div className="container mx-auto p-6 space-y-6">
          {/* Header */}
          <div className="flex justify-between items-center">
            <div>
              <h1 className="text-3xl font-bold">{t('contractUpdates.title', '合約更新')}</h1>
              <p className="text-gray-600 mt-1">
                {t('contractUpdates.description', '管理智能合約參數更新 - 包含黑名單管理功能')}
              </p>
            </div>
            <div className="flex items-center gap-2">
              <Button variant="outline" size="sm">
                <RefreshCw className="w-4 h-4 mr-2" />
                {t('contractUpdates.refreshStatus', '刷新狀態')}
              </Button>
            </div>
          </div>

          {/* Security Warning */}
          <Alert className="border-red-200 bg-red-50">
            <AlertTriangle className="h-4 w-4" />
            <AlertDescription>
              <strong>{t('contractUpdates.securityNotice', '安全提醒')}:</strong> {t('contractUpdates.securityNotice', '合約更新直接修改區塊鏈狀態。所有更新都會被記錄並可審計。只有授權管理員才能提交更新。')}
            </AlertDescription>
          </Alert>

      {/* Contract Selection */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        {contractList.map(([key, contract]) => (
          <Card 
            key={key} 
            className={`cursor-pointer transition-all ${
              activeContract === key ? 'ring-2 ring-blue-500' : 'hover:shadow-md'
            }`}
            onClick={() => setActiveContract(key)}
          >
            <CardHeader className="pb-3">
              <div className="flex justify-between items-start">
                <CardTitle className="text-lg">{contract.name}</CardTitle>
                {getRiskBadge(contract.riskLevel)}
              </div>
            </CardHeader>
            <CardContent>
              <p className="text-sm text-gray-600 mb-3">{contract.description}</p>
              <div className="text-xs text-gray-500 mb-2">
                {contract.address.substring(0, 10)}...{contract.address.substring(32)}
              </div>
              <div className="text-xs text-blue-600">
                {contract.updateableParams.length} {t('contractUpdates.updateableParameters', '可更新參數')}
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* Contract Management Tabs */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Settings className="w-5 h-5" />
            {t('contractUpdates.contractManagement', '{{contractName}} 管理', { contractName: contractInfo[activeContract as keyof typeof contractInfo].name })}
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="mb-4 p-4 bg-gray-50 rounded-lg">
            <h3 className="font-medium mb-2">{t('contractUpdates.contractInfo', '合約信息')}</h3>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm">
              <div>
                <span className="font-medium">{t('contractUpdates.contractAddress', '地址')}:</span>
                <br />
                <span className="font-mono text-xs">
                  {contractInfo[activeContract as keyof typeof contractInfo].address}
                </span>
              </div>
              <div>
                <span className="font-medium">{t('contractUpdates.contractRiskLevel', '風險級別')}:</span>
                <br />
                {getRiskBadge(contractInfo[activeContract as keyof typeof contractInfo].riskLevel)}
              </div>
              <div>
                <span className="font-medium">{t('contractUpdates.updateableParameters', '可更新參數')}:</span>
                <br />
                <span className="text-blue-600">
                  {contractInfo[activeContract as keyof typeof contractInfo].updateableParams.length} {t('contractUpdates.parameters', '參數')}
                </span>
              </div>
            </div>
          </div>

          <Tabs defaultValue={activeTab} className="w-full">
            <TabsList className="grid w-full grid-cols-2">
              <TabsTrigger value="updates" className="flex items-center gap-2">
                <Settings className="w-4 h-4" />
                {t('contractUpdates.contractUpdatesTab', '合約更新')}
              </TabsTrigger>
              <TabsTrigger value="monitoring" className="flex items-center gap-2">
                <Activity className="w-4 h-4" />
                {t('contractUpdates.systemMonitoring', '系統監控')}
              </TabsTrigger>
            </TabsList>
            
            <TabsContent value="updates" className="mt-6">
              <ContractUpdateManager contractName={activeContract} />
            </TabsContent>
            
            <TabsContent value="monitoring" className="mt-6">
              <ContractMonitoringDashboard />
            </TabsContent>
          </Tabs>
        </CardContent>
      </Card>
        </div>
      </AdminGuard>
    </DashboardLayout>
  );
};

export default ContractUpdatesPage;